package com.ews.onlineexchange.controller;

import java.util.ArrayList;
import java.util.List;

import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.ews.onlineexchange.model.User;
import com.ews.onlineexchange.service.UserService;
import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.ServiceBuyer;
import com.ews.onlineexchange.service.EntityQuery;

@Model
public class ServiceBuyerList extends EntityQuery<ServiceBuyer> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public ServiceBuyerList() {
		setOrder("auditted DESC,createDate desc");
		setMaxResults(MAX_RESULTS_NORMAL);
	}
	
	@Inject
	EntityManager entityManager;
	private String QUERY_UNAUDIT_BUYER_EQL = "SELECT serviceBuyer FROM ServiceBuyer serviceBuyer "+
			" WHERE auditted IS NULL ORDER BY createDate DESC";
	private int MAX_SIZE = 7;		
	public List<ServiceBuyer> getUnauditBuyers(){
	return entityManager.createQuery(QUERY_UNAUDIT_BUYER_EQL).setMaxResults(MAX_SIZE).getResultList();
	
	
	}
	@Inject
	UserService userService;
	@Override
	protected List<Predicate> getRestrictions(CriteriaBuilder cb, Root<ServiceBuyer> entity) {
		List<Predicate> restrictions = new ArrayList<Predicate>();

		User user = userService.getLoginedUser();
		if(user != null){
			String userRegion = user.getRegion();
//			if("370501".equals(userRegion))restrictions.add(cb.or(cb.equal(entity.get("region"), user.getRegion()),cb.equal(entity.get("region"),"000000")));
//			else restrictions.add(cb.equal(entity.get("region"), user.getRegion()));
			if(!"370501".equals(userRegion))restrictions.add(cb.equal(entity.get("region"), user.getRegion()));
		}
		if(StringUtils.isNotBlank(getRegion())){
			restrictions.add(cb.equal(entity.get("region"), getRegion()));
		}
		String buyerName = (String)getParameterValues().get("buyerName");
		if (!StringUtils.isBlank(buyerName))
			restrictions.add(cb.like(entity.get("cnname"), getStringRestriction(buyerName)));
		String auditStatus = (String)getParameterValues().get("auditStatus");
		if(!"2".equals(auditStatus)) {
			if(StringUtils.isBlank(auditStatus)) {
				restrictions.add(cb.isNull(entity.get("auditted")));
			}else if ("0".equals(auditStatus)) {
				restrictions.add(cb.isFalse(entity.<Boolean>get("auditted")));
			}else {
				restrictions.add(cb.isTrue(entity.<Boolean>get("auditted")));
			}
		}
		return restrictions;
	}
	
	
}
